<template>
  <div class="header">
    <div class="logo">
      <span>点餐系统</span>
      <span style="color: #056547">{{role}}</span>
    </div>
    <div class="user-info">
      <el-dropdown trigger="click" @command="handleCommand">
      <span class="el-dropdown-link">
         <img class="user-logo" :src="imgUrl" >
        <h3>{{ username }}</h3>
      </span>
        <el-dropdown-menu>
          <el-dropdown-item command="loginOut">退出</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Header',
  data () {
    return {
      imgUrl: ''
    }
  },
  mounted () {
    if (sessionStorage.getItem('phone') === null) {
      this.$message.error('您尚未登录，请先登录!')
      this.$router.push('/Login')
      return
    }
    let avatar = sessionStorage.getItem('avatar')
    if (avatar !== '') {
      this.imgUrl = this.$url + avatar
    }
  },
  // 利用计算属性获取用户名和用户类型
  computed: {
    // 从sessionStorage获取用户名
    username () {
      let username = sessionStorage.getItem('user_name')
      return username || this.name
    },
    role () {
      if (sessionStorage.getItem('is_admin') === '1') {
        return '管理员'
      } else {
        return '用户'
      }
    }
  },
  methods: {
    handleCommand (command) {
      if (command === 'loginOut') {
        this.$request.get('/user/logout')
        sessionStorage.removeItem('phone')
        sessionStorage.removeItem('user_name')
        sessionStorage.removeItem('avatar')
        sessionStorage.removeItem('is_admin')
        this.$router.push('/Login')
      }
    }
  }
}
</script>

<style scoped>
.header {
  width: 100%;
  height: 70px;
  font-size: 22px;
  line-height: 70px;
  background-image: linear-gradient(-20deg, #616161 0%, #9bc5c3 100%);
}

.logo {
  float: left;
  width: 200px;
  height: 70px;
  margin-left: 60px;
  text-align: center;

  display: flex;
  justify-content: space-between;
}

.user-info {
  float: right;
  width: 200px;
  height: 70px;
  padding-right: 10px;
  font-size: 16px;
  color: #fff;
}

.user-logo {
  position: absolute;
  left: 0;
  top: 10px;
  width: 50px;
  height: 50px;
  border-radius: 50%;
}

.el-dropdown-link {
  position: relative;
  display: inline-block;
  padding-left: 60px;
  color: #fff;
  cursor: pointer;
  vertical-align: middle;
}
</style>
